package com.jiyun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.dto.EmpDto;
import com.jiyun.entity.Dept;
import com.jiyun.entity.Emp;
import com.jiyun.entity.SalaryConstructor;
import com.jiyun.service.IDeptService;
import com.jiyun.service.IEmpService;
import com.jiyun.service.ISalaryConstructorService;
import com.jiyun.service.IShiguService;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  控制层
 * </p>
 *
 * @author 聪哥哥
 * @since 2023-03-10
 */
@RestController
@RequestMapping("/emp")
public class EmpController {

    @Autowired
    IEmpService empService;

    /**
     * 添加接口
     */
    @RequestMapping("/add")
    public void addEmp(@RequestBody Emp emp){
        empService.save(emp);
    }

    /**
     * 修改接口
     */
    @RequestMapping("/update")
    public void updateEmp(@RequestBody Emp emp){
        empService.updateById(emp);
    }

    /**
     * 单个删除接口
     */
    @RequestMapping("/deleteOne")
    public void deleteOne(@RequestParam Integer id){
        empService.removeById(id);
    }

    /**
     * 批量删除接口
     * 前台ajax参数ids传入示例：1,2,3  (英文逗号分隔的字符串)
     */
    @RequestMapping("/deleteBatch")
    public void deleteBatch(@RequestParam List<Integer> ids){
        empService.removeByIds(ids);
    }

    /**
     * 根据id查询实体接口
     */
    @RequestMapping("/findById")
    public Emp findById(@RequestParam Integer id){
        return empService.getById(id);
    }

    /**
     * 查询所有接口
     */
    @RequestMapping("/findAll")
    public List<Emp> findAll(){
        return empService.list();
    }

    /**
     * 分页查询接口
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     */
    @RequestMapping("/findPage")
    public Page<EmpDto> findPage(@RequestParam Integer page, @RequestParam Integer pageSize){
        Page<Emp> empPage = new Page<>(page, pageSize);
        empService.page(empPage);





        Page<EmpDto> empDtoPage = new Page<>(page, pageSize);
        empDtoPage.setTotal(empPage.getTotal());

        List<Emp> empList = empPage.getRecords();

        ArrayList<EmpDto> empDtoList = new ArrayList<>();

        for (Emp emp : empList) {
            EmpDto empDto = new EmpDto();
            //复制基本属性
            BeanUtils.copyProperties(emp,empDto);

            //组装部门名称
            String deptNames = "";
            for (String did : emp.getDeptIds().split(",")) {
                Dept dept = deptService.getById(did);
                deptNames+=dept.getName()+"-";
            }
            deptNames = deptNames.substring(0,deptNames.length()-1);
            empDto.setDeptNames(deptNames);

            //查询薪资结构,注意数据库添加的薪资结构数据，一个部门只能有一个薪资结构
            LambdaQueryWrapper<SalaryConstructor> salaryConstructorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            salaryConstructorLambdaQueryWrapper.eq(SalaryConstructor::getDeptIds,emp.getDeptIds());
            SalaryConstructor salaryConstructor = salaryConstructorService.getOne(salaryConstructorLambdaQueryWrapper);
            empDto.setSalaryConstructor(salaryConstructor);
            empDtoList.add(empDto);
        }

        empDtoPage.setRecords(empDtoList);
        return empDtoPage;



    }

    @Autowired
    ISalaryConstructorService salaryConstructorService;

    @Autowired
    IDeptService deptService;

    @RequestMapping("login")
    public Object login(@RequestParam Boolean isHr,@RequestBody Emp emp){
        /**
         *
         * 先看账号是否存在
         * 在看密码是否正确
         * 身份是否正确
         */

        LambdaQueryWrapper<Emp> empLambdaQueryWrapper = new LambdaQueryWrapper<>();
        empLambdaQueryWrapper.eq(Emp::getWorknum,emp.getWorknum());
        Emp empDB = empService.getOne(empLambdaQueryWrapper);
        if (empDB==null) {
            return "账号不存在";
        }

        if(!(emp.getIdcard().length()==6&&empDB.getIdcard().endsWith(emp.getIdcard()))){
            return "密码不正确";
        }

        if (isHr) {
            if (!empDB.getDeptIds().equals("1,2")) {
                return "你好像不是HR";
            }
        }else{
            if (empDB.getDeptIds().equals("1,2")) {
                return "你好像是HR";
            }
        }


        return empDB;

    }

    @RequestMapping("exportSalary")
    public void exportSalary(HttpServletResponse response) throws Exception {

        /**
         * 1、准备数据
         * 2、获取模板，写入数据
         */

        Page<EmpDto> empDtoPage = findPage(1,9999);

        List<EmpDto> empDtoList = empDtoPage.getRecords();


        XSSFWorkbook workbook = new XSSFWorkbook(EmpController.class.getResourceAsStream("/salary_template.xlsx"));

        XSSFSheet sheet = workbook.getSheetAt(0);

        int rowNum = 2;
        for (EmpDto empDto : empDtoList) {
            XSSFRow row = sheet.createRow(rowNum++);
            int cellNum = 0;
            XSSFCell cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getName());

            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getWorknum());

            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getJibengongzi());

            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getJiaotongbuzhu());

            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getJiangjin());

            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getWucanbuzhu());

            //扣款
            Integer shiguKoukuan = shiguService.findAllKoukuanByEid(empDto.getId());
            cell = row.createCell(cellNum++);
            cell.setCellValue(shiguKoukuan);


            //养老金
            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getYanglaojinbili());
            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getYanglaojinjishu());
            Double yanglaojinKoukuan = Double.parseDouble(empDto.getSalaryConstructor().getYanglaojinbili())*Double.parseDouble(empDto.getSalaryConstructor().getYanglaojinjishu());
            cell = row.createCell(cellNum++);
            cell.setCellValue(yanglaojinKoukuan);


            //医疗保险
            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getYiliaobaoxianbili());
            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getYiliaobaoxianjishu());
            Double yiliaobaoxianKoukuan = Double.parseDouble(empDto.getSalaryConstructor().getYiliaobaoxianbili())*Double.parseDouble(empDto.getSalaryConstructor().getYiliaobaoxianjishu());
            cell = row.createCell(cellNum++);
            cell.setCellValue(yiliaobaoxianKoukuan);


            //公积金
            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getGongjijinbili());
            cell = row.createCell(cellNum++);
            cell.setCellValue(empDto.getSalaryConstructor().getGongjijinjishu());
            Double gongjijinKoukuan = Double.parseDouble(empDto.getSalaryConstructor().getGongjijinbili())*Double.parseDouble(empDto.getSalaryConstructor().getGongjijinjishu());
            cell = row.createCell(cellNum++);
            cell.setCellValue(gongjijinKoukuan);


            //应发工资
            Integer yingfaGongzi = Integer.parseInt(empDto.getSalaryConstructor().getJibengongzi())
                    +Integer.parseInt(empDto.getSalaryConstructor().getJiaotongbuzhu())
                    +Integer.parseInt(empDto.getSalaryConstructor().getJiangjin())
                    +Integer.parseInt(empDto.getSalaryConstructor().getWucanbuzhu());

            //个人所得税

            Double geshui = 0d;
            Integer yingshuijine = yingfaGongzi-5000;
            if(yingfaGongzi<5000){
                geshui = 0d;
            }else if(yingshuijine<3000){
                geshui = yingshuijine*0.04;
            }else if(yingshuijine>=3000&&yingshuijine<20000){
                geshui = yingshuijine*0.08;
            }else if(yingshuijine>=20000){
                geshui = yingshuijine*0.12;
            }

            cell = row.createCell(cellNum++);
            cell.setCellValue(geshui);

            //应发工资

            cell = row.createCell(cellNum++);
            cell.setCellValue(yingfaGongzi);

            //实发工资
            Double shifagongzi = yingfaGongzi-shiguKoukuan-yanglaojinKoukuan-yiliaobaoxianKoukuan-gongjijinKoukuan-geshui;
            cell = row.createCell(cellNum++);
            cell.setCellValue(shifagongzi);
        }

        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("工资条.xlsx", "UTF-8"));
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");
        workbook.write(response.getOutputStream());

    }

    @Autowired
    IShiguService shiguService;

}
